<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\Exception;
use StarCloud\Library\HttpCurl;
use StarCloud\Models\Doumvip\AppCookie;

class YingyongbaoBot
{
    use HttpCurl;

    /* @var $httpClient HttpClient */
    private $httpClient = null;
    private $promotionProjectId = 32019730;
    const HWK_PROJECT_ID = 26020941;

    public function __construct($promotionProjectId = 32019730)
    {
        if (!empty($promotionProjectId)) {
            $this->promotionProjectId = $promotionProjectId;
        }
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function getOrders($dayTime, $page)
    {
//        $firstDayOfMonth = strtotime(date('Y-m-01 00:00:00')) * 1000;
        $firstDayOfMonth = strtotime(date('Y-m-d', (strtotime(date('Y-m-01 00:00:00')) - 3*86400))) * 1000;

        $lastDayOfMonth = strtotime(date('Y-m-t 23:59:59')) * 1000;
        $url = "https://kol.open.qq.com/api/xy/runtime/env/prod/manage/datasource/collection/request/yyb_kol_center_web/data-manage/cmd_data/list";
        $body = [
            "endTime" => $lastDayOfMonth,
            'startTime' => $firstDayOfMonth,
            'page' => $page,
            'pageSize' => 20,
        ];


        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['data']['list'])) {
            return $json['data']['list'];
        }

        return false;
    }

    public function checkPlatform($platform)
    {
       $config = $this->getConfig();
       foreach ($config['platforms'] as $item) {
           if (intval($item['id']) == intval($platform)) {
               return true;
           }
       }

       return false;
    }

    public function getContentTypeName($platformId)
    {
        $config = $this->getConfig();
        foreach ($config['accountContentDirection'] as $item) {
            if (intval($item['id']) == intval($platformId)) {
                return $item['label'];
            }
        }

        return "";
    }

    public function getPlatformName($platformId)
    {
        $config = $this->getConfig();
        foreach ($config['platforms'] as $item) {
            if (intval($item['id']) == intval($platformId)) {
                return $item['label'];
            }
        }

        return "";
    }
    public function checkContentType($type)
    {
        $config = $this->getConfig();
        foreach ($config['accountContentDirection'] as $item) {
            if (intval($item['id']) == intval($type)) {
                return true;
            }
        }

        return false;
    }

    public function getItemByKeyword($keyword)
    {
        $url = "https://kol.open.qq.com/api/xy/runtime/env/prod/manage/datasource/collection/request/yyb_kol_center_web/command/cmd/list";
        $body = [
            "shortCmd" => $keyword,
            'promotionProjectIds' => [],
            'page' => 1,
            'pageSize' => 10,
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        var_dump($json);

        if (isset($json['data']['list'][0])) {
            return $json['data']['list'][0];
        }

        return false;
    }

    public function checkMaterial($name)
    {
        $url = 'https://kol.open.qq.com/api/xy/runtime/env/prod/manage/datasource/collection/request/yyb_kol_center_web/command/material/request';

        $body = [
            'promotionProjectId' => $this->promotionProjectId,
            'page' => 1,
            'pageSize' => 20,
            'keyword' => $name
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        Di::getDefault()->get("logger")->info("checkMaterial" . json_encode($body) . json_encode($json));

        if (isset($json['data']['list'])) {
            return $json['data']['list'];
        }

        return [];
    }

    public function getConfig()
    {
            return [
            'posts' => [
                ['id' => 1, 'label'=> '视频/图文链接', 'type' => 1],
                ['id' => 2, 'label'=> '直播截图', 'type' => 2],
            ],
            'platforms' => [
                ['id' => '1', 'label'=> '抖音',],
                ['id' => '2', 'label'=> '视频号',],
                ['id' => '3', 'label'=> '快手',],
                ['id' => '4', 'label'=> '小红书',],
                ['id' => '5', 'label'=> 'B站',]
            ],
            'accountContentDirection' => [
                ['id' => '1', 'label'=> '游戏技巧教学',],
                ['id' => '2', 'label'=> '游戏剧情解说',],
                ['id' => '3', 'label'=> '搞笑集锦',],
                ['id' => '4', 'label'=> '游戏资讯',],
                ['id' => '5', 'label'=> '游戏福利',],
                ['id' => '6', 'label'=> '小说',],
                ['id' => '7', 'label'=> '影视综',],
                ['id' => '8', 'label'=> '生活vlog',],
                ['id' => '9', 'label'=> '游戏测评',],
                ['id' => '10', 'label'=> '游戏真人',],
                ['id' => '11', 'label'=> '游戏动漫',],
                ['id' => '12', 'label'=> '赛事集锦',],
                ['id' => '13', 'label'=> '游戏直播切片',],
            ]
        ];

    }

    public function getHeader()
    {
        return [
            'Content-Type' => 'application/json',
            'Cookie' => AppCookie::getAppCookie(AppCookie::APPID_YYB),
        ];
    }

    public function cos()
    {
        $url = 'https://kol.open.qq.com/api/xy/runtime/env/prod/manage/datasource/collection/request/yyb_kol_center_web/command/cos/request';
        $body = [];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        return $json['data'];
    }

    public function createLink($cmdId, $type, $platform, $content, $ext)
    {
        $url = "https://kol.open.qq.com/api/xy/runtime/env/prod/manage/datasource/collection/request/yyb_kol_center_web/command/promotion_backfill/create";
        $ext[] =  ['type' => intval($type), 'content' => $content, 'mediaPlatform' => intval($platform)];


        $newExt = [];
        foreach ($ext as $item) {
            $item['type'] = 1;
            $newExt[] = $item;
        }
        $body = [
            "cmdId" => $cmdId,
            "backfillInfos" => $newExt
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['ret']) && $json['ret'] == 0) {
            return $ext;
        }

        throw new Exception(9999, $json['msg'] ?? "系统错误");
    }
    public function getMembers($page)
    {
        $url = 'https://kol.open.qq.com/api/xy/runtime/env/prod/manage/datasource/collection/request/yyb_kol_center_web/kolmanage/kol/list';

        $body = [
            'page' => $page,
            'pageSize' => 10,
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        return $json;
    }

    public function createMember($name, $kolAbbr, $homeLink)
    {
        $url = "https://kol.open.qq.com/api/xy/runtime/env/prod/manage/datasource/collection/request/yyb_kol_center_web/kolmanage/kol/create";
        $body = [
            "homeLink" => $homeLink,
            "kolAbbr" => $kolAbbr,
            "kolName" => $name
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        Di::getDefault()->get("logger")->info("yyb createMember" . json_encode($body) .  ' respons' . json_encode($json));

        if (isset($json['data']['id'])) {
            return $json['data'];
        }
        throw new Exception(9999, $json['msg'] ?? "系统错误");

        return false;
    }

    public function resource($page, $keyword = "")
    {
        $url = 'https://kol.open.qq.com/api/xy/runtime/env/prod/manage/datasource/collection/request/yyb_kol_center_web/command/material/request';
        $body = [
            'promotionProjectId' => $this->promotionProjectId,
            'page' => $page,
            'pageSize' => 10,
            'keyword' => "",
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data']['list'])) {
            return $json['data']['list'];
        }

        return [];
    }

    public function checkChannelId($platform, $content_type)
    {
        $url = 'https://kol.open.qq.com/api/xy/runtime/env/prod/manage/datasource/collection/request/yyb_kol_center_web/command/cmd/custom_channel';

        $body = [
            'promotionProjectId' => $this->promotionProjectId,
            'accountContentDirection' => $content_type,
            'mediaPlatform' => $platform,
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data']['channelId'])) {
            return $json['data']['channelId'];
        }

        throw new Exception(9999, $json['msg'] ?? "系统错误");
    }

    public function getListByKeyword($keyword)
    {

    }
    public function createKeyword($kolId, $platform, $content_type, $materialId)
    {
        $materialIds = $this->checkMaterial($materialId);
        if (empty($materialIds) || count($materialIds) != 1) {
            throw new Exception(9999, '残局ID错误');
        }
        $materialId = $materialIds[0]['id'];
        $materialInfo = $materialIds[0];
        $channelId = $this->checkChannelId($platform, $content_type);

        $url = 'https://kol.open.qq.com/api/xy/runtime/env/prod/manage/datasource/collection/request/yyb_kol_center_web/command/cmd/create';

        $body = [
            'channelId' => $channelId,
            'promotionProjectId' => $this->promotionProjectId,
            'kolId' => $kolId,
            'materialId' => $materialId,
            'validTime' => strtotime('+1 year'),
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        Di::getDefault()->get('logger')->info("yyb_create_keyword" . json_encode($json) . ' body:' . json_encode($body));

        if (isset($json['ret']) && $json['ret'] == 0) {
            return [
                'data' => $json['data'],
                'materialInfo' => $materialInfo,
            ];
        }

        throw new Exception(9999, $json['msg'] ?? "系统错误");

    }
}